package com.example.mall.adapter

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import com.bumptech.glide.Glide
import com.example.mall.DetailActivity
import com.example.mall.R
import com.example.mall.entity.GoodsInfo


class GoodsAdapter(var mContext: Context, var mGoodsInfo: List<GoodsInfo>, var mAddCartListener : AddCartListener) : BaseAdapter() {
    override fun getCount(): Int {
        return mGoodsInfo.size
    }

    override fun getItem(position: Int): Any {
         return position
    }

    override fun getItemId(position: Int): Long {
        return position.toLong()
    }

    override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {

        val info = mGoodsInfo.get(position)
        var view = convertView
        var holder : ViewHolder? = null

        if(view == null) {
            view = LayoutInflater.from(mContext).inflate(R.layout.item_goods, null)
            holder = ViewHolder()
            holder.iv_thumb = view.findViewById<ImageView>(R.id.iv_thumb)
            holder.tv_name = view.findViewById<TextView>(R.id.tv_name)
            holder.tv_price = view.findViewById<TextView>(R.id.tv_price)
            holder.btn_add = view.findViewById<Button>(R.id.btn_add)
            view.tag = holder
        }else{
            holder = view.getTag() as ViewHolder
        }

        //holder.iv_thumb?.setImageURI(Uri.parse(info.picPath))
        Glide.with(view!!.context).load(info.picPath).into(holder.iv_thumb!!)
        //holder.iv_thumb?.setImageResource(info.pic)
        holder.tv_name?.setText(info.name)
        holder.tv_price?.setText(info.price.toInt().toString())
        holder.btn_add?.setOnClickListener { v ->
            mAddCartListener.addToCart(info.id)
        }

        holder.iv_thumb?.setOnClickListener{v ->
            val intent = Intent(mContext,DetailActivity::class.java)
            intent.putExtra("goods_id",info.id)
            mContext.startActivity(intent)
        }
        return view
    }

    class ViewHolder(
        var iv_thumb : ImageView? = null,
        var tv_name : TextView? = null,
        var tv_price : TextView? = null,
        var btn_add : Button? = null,

    )

    interface AddCartListener{
        fun addToCart(goodsId: Int)
    }
}